<template>

    <div class="weui-cells">
        <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">小组名称</label></div>
            <div class="weui-cell__bd">
                <input v-model="item.name" class="weui-input" value="{{item.name}}" type="text" placeholder="必填" maxlength="20">
            </div>
        </div>
        <a @click="selectParentGroup" class="weui-cell weui-cell_access">
            <div class="weui-cell__bd">
                <p><span class="title">上级小组</span><span :value="item.pid">{{item.parent_name}}</span></p>
            </div>
            <div class="weui-cell__ft"></div>
        </a>
        <a @click="selectLeader" class="weui-cell weui-cell_access">
            <div class="weui-cell__bd">
                <p><span class="title">小组组长</span><span :class="{placeholder : !leaderStr}">{{leaderStr || '未设置'}}</span></p>
            </div>
            <div class="weui-cell__ft"></div>
        </a>
    </div>
    <div class="weui-cells__title">* 小组组长可以对所属小组及以下小组的人员进行管理，并且可以查看管理范围内的应用数据</div>

    <div class="btn-wrap">
        <a @click="getHasSubGroupOrMember" class="weui-btn weui-btn_warn">删除小组</a>
    </div>

</template>

<script>
    /**
     *  引入工具类库 或 Native API
     *  example : import widget from 'gapi/widget'
     */
    import $ from 'zepto'
    import cache from 'gapi/cache'
    import clientInfo from 'gapi/clientInfo'
    import * as util from 'js/util.js'
    import userCenterApi from 'clientApi/userCenterApi'
    import clientUi from 'gapi/clientUi'
    import widget from 'gapi/widget'
    import commonPage from 'clientApi/commonPage.js'
    /**
     *  引入组件 以及 组件接口(Action)
     *  example : import Somecomponents from 'components/Somecomponents/Somecomponents'
     */

    /**
     *  组件实例对象
     */
    export default {
        components: {

        },
        data: function(){
            return{
                // item: {
                //   parentId: '',
                //   parentName: '',
                //   groupLeaders: [],
                // }
                leaderIds: [],
                item: {
                    "id": "",
                    "name": "",
                    "team_id": "",
                    "project_id": "",
                    "depth": "",
                    "pid": "",
                    "leader": [
                          // {
                          //     "user_id": "19",
                          //     "name": "小白"
                          // }
                    ],
                    "parent_name":""
              },
              delBackWebViewId:'',
              _type:''
            }
        },
        computed: {
            leaderStr: function(){
                return this.item.leader.map((o, i, a) => {
                    return o.name
                }).join(',')
            },
            leaderIdArr: function(){
                return this.item.leader.map((o, i, a) => {
                    return o.user_id
                })
            }
        },
        vuex: {
            getters: {

            },
            actions: {

            }
        },
        methods: {
            /**
             * 初始化
             * @method init
             * @public
             * @return {Null} void
             */
            init (){
                this.teamId = util.getUrddataString('team_id')
                this.projectId = util.getUrddataString('project_id')
                this.groupId = util.getUrddataString('groupid')
                this.delBackWebViewId = util.getUrddataString('webViewId')
                cache.setMemoryCache('KqCacheMessge',{
                    team_id: this.teamId,
                    project_id: this.projectId
                })
                commonPage.getWebViewID((data)=>{
                    cache.setMemoryCache('webViewID',{'webViewID':data})
                })
                //获取小组信息
                this.getGroupInfo()

            },
            //更新小组 && 组长
            updateData (data){
                let key = data.key
                let value = data.value
                let filterData = []
                // alert(JSON.stringify(value))
                this._type = data.type
                switch(key){
                    case 'selectGroup':
                        this.item.pid = value.id
                        this.item.parent_name = value.name
                    break
                    case 'participantMember':
                        this.leaderIds = value
                        cache.getMemoryCache('allMemberList',(data)=>{
                            
                            filterData = data.filter((o, i, a) => {
                                for(let id in this.leaderIds){
                                    if(this.leaderIds[id] == o.user_id){
                                        return true
                                    }
                                }
                            })
                            
                            this.item.leader = filterData.map((o, i, a) => {
                                return {
                                    user_id: o.user_id,
                                    name: o.nick_name
                                }
                            })
                        })
                } 
            },
            //选择上级小组
            selectParentGroup (){
                location.href = "dmsaas://GroupSelectSingle?urdData=" + encodeURIComponent(`group_id=${this.groupId}`)
            },
            //选择组长
            selectLeader (){
                // cache.setMemoryCache('participantMember', this.leaderIdArr)
                cache.setMemoryCache('participantMember', this.leaderIdArr)
                location.href = "dmsaas://KaoqinAddMember"
            },
            // todo: 获取小组设置信息 (wait server add this api)
            getGroupInfo (){
              util.ajax({
                    url:'/group/info',
                    type:'GET',
                    data:{
                        team_id : this.teamId,
                        project_id : this.projectId,
                        group_id : this.groupId,
                    },
                    timeout:10000,
                    beforeSend: () => {

                    },
                    success:(result) => {
                        if(result.errno == 0){
                            this.item = result.data
                        }else{
                            widget.toast(result.errmsg)
                        }
                    },
                    error: (xhr, status) => {
                      var toastStr = '';
                      if(status == 'timeout'){
                          toastStr = '网络请求超时'
                      }else{
                          toastStr = '服务器异常'
                      }

                      widget.toast(toastStr)
                    },
                    complete: () => {

                    },
                    noNetwork: () => {
                        // 无网络的回调
                        widget.toast('网络连接失败，请检查网络')
                    }
                })
            },
            getHasSubGroupOrMember(){
              util.ajax({
                url:'/group/descendant_empty',
                type:'GET',
                data:{
                    team_id : this.teamId,
                    project_id : this.projectId,
                    group_id : this.groupId,
                },
                timeout:10000,
                success:(result) => {
                    if(result.errno == 0){
                      this.delGroup()
                    }else if(result.errno == '11014'){
                      widget.toast('需要先删除小组下的成员和小组，再删除该小组')//该小组下有成员
                    }else{
                      widget.toast('服务器异常')
                    }
                },
                error: (xhr, status) => {
                  var toastStr = '';
                  if(status == 'timeout'){
                      toastStr = '网络请求超时'
                  }else{
                      toastStr = '服务器异常'
                  }

                  widget.toast(toastStr)
                },
                noNetwork: () => {
                    widget.toast('网络连接失败，请检查网络')
                }
              })
            },
            //删除小组
            delGroup(){//todo
                clientUi.showDialog('删除小组', '是否确认?', (data) => {
                    if(data.status==1){
                      util.ajax({
                          url:'/group/delete',
                          type:'POST',
                          data:{
                              team_id: this.teamId, //todo 找服务端确认需要的参数
                              project_id : this.projectId,
                              group_id : this.groupId
                          },
                          timeout:10000,
                          beforeSend: () => {

                          },
                          success:(result) => {
                              console.log(result)
                              if(result.errno == 0){
                                widget.toast('删除成功')
                                if(this.delBackWebViewId){
                                  commonPage.goBack(1, {}, this.delBackWebViewId)
                                }
                              }else{
                                widget.toast(result.errmsg)
                              }
                          },
                          error: (xhr, status) => {
                              // error
                              var toastStr = '';
                              if(status == 'timeout'){
                                  toastStr = '网络请求超时'
                              }else{
                                  toastStr = '服务器异常'
                              }

                              widget.toast(toastStr)
                          },
                          complete: () => {

                          },
                          noNetwork: () => {
                              // 无网络的回调
                              widget.toast('网络连接失败，请检查网络')
                          }
                      })
                    }
                }, '确定', '取消')
            },
            doSubmit (){
                //校验
                if (this.item.name == ''){
                    widget.toast('请输入小组名称')
                    return
                }else if (this.item.parent_name == ''){
                    widget.toast('请选择上级小组')
                    return
                }
                util.ajax({
                    url:'/group/member_exists',
                    type:'GET',
                    data:{
                        team_id: this.teamId,
                        group_id: this.groupId,
                        project_id : this.projectId,
                        user_ids : JSON.stringify(this.leaderIdArr)
                    },
                    timeout:10000,
                    beforeSend: () => {
                    },
                    success:(result) => {
                        if(result.errno == 11031){
                            clientUi.showDialog('添加组长', '选择的成员不在该组，是否将其移动至该小组?', (data) => {
                                 if (data.status == 1) {
                                     execSave.call(this);
                                 }
                             });
                        } else if (result.errno == 0) {
                            execSave.call(this);
                        }
                    },
                    error: (xhr, status) => {
                        // error
                        console.log(xhr)
                    },
                    complete: () => {

                    },
                    noNetwork: () => {
                        // 无网络的回调
                        widget.toast('网络连接失败，请检查网络')
                    }
                })

              function execSave() {
                  util.ajax({
                      url:'/group/edit',
                      type:'POST',
                      data:{
                          group_name: this.item.name,
                          parent_id: this.item.pid,
                          group_leader: this.leaderIdArr.join(','),
                          team_id: this.teamId,
                          group_id: this.groupId,
                          project_id : this.projectId,
                      },
                      timeout:10000,
                      beforeSend: () => {

                      },
                      success:(result) => {
                          // alert(JSON.stringify(result))
                          if(result.errno == 0){
                              widget.toast('修改成功')
                              commonPage.goBack(1, {groupName: this.item.name,pream:this._type})
                          }else{
                              commonPage.goBack(0)
                              widget.toast('修改失败')
                          }
                          
                      },
                      error: (xhr, status) => {
                          // error
                          console.log(xhr)
                      },
                      complete: () => {

                      },
                      noNetwork: () => {
                          // 无网络的回调
                          widget.toast('网络连接失败，请检查网络')
                      }
                  })
              }

            }
        },
        created(){
            commonPage.updateTitleBar({
                  backAction: '',
                  leftDisplay: false,
                  leftText: '',
                  leftAction: '',
                  rightDisplay: true,
                  rightText: '保存',
                  rightAction: 'doSubmit'
            })
            this.init();
            window.loadData = this.updateData
            window.doSubmit = this.doSubmit
        }

    }


</script>

<!-- CSS 样式 -->
<style src="../../node_modules/weui/dist/style/weui.css"></style>
<style src="../../static/css/common.css"></style>
<style>
    body{
        background: #f2f2f2;
    }
    .weui-cells.last-cell{
        margin-top: 0;
    }
    .btn-wrap{
        padding: 20px 12px 0;
    }
</style>
